<?php

# http://projects:8081/cdapp-hole-api/api/login.php

include_once "_portal.php";

if (
  isset($_GET["output"]) &&
  $_GET["output"] == "login" &&
  isset($post->username) &&
  $post->username != "" &&
  isset($post->password) &&
  $post->password != ""
) {
  $result = login($post->username, $post->password);
  $result['rx'] = $post;
  output($result);
}

function login($username, $password) {
  $status = 0;
  $user = null;
  $msg = 'unknown error';

  $sql = '';
  if (is_numeric($username)) {
    $username2 = $username . '';
    $username2 = substr($username2, 0, 4) . substr($username2, strlen($username) - 3, 3);
    $sql = "SELECT * FROM `oprec_security_data` WHERE (`number` = {$username} OR `number` = {$username2}) AND `disposed` = 0";
  } else {
    $sql = "SELECT * FROM `oprec_security_data` WHERE `name` = '{$username}' AND `disposed` = 0";
  }
  $res = exec_sql($sql);

  if ($res && count($res) == 1) {
    if ($res[0]['passwd'] == $password) {
      $status = 1; // ok
      $user = $res[0];
      $msg = 'ok';
    } else {
      $status = -1; // password error
      $msg = 'password error';
    }
  } else {
    $status = -2; // username error
    $msg = 'username error';
  }
  $result = array(
    'status' => $status,
    'user' => $user,
    'msg' => $msg,
  );
  return $result;
}